package com.csy.user.entity.system.service.impl;

import com.csy.commons.core.exception.BaseException;
import com.csy.commons.dto.LoginUser;
import com.csy.commons.dto.SysUser;
import com.csy.commons.enums.UserStatus;
import com.csy.user.entity.system.service.SysUserService;
import com.csy.commons.framework.service.SysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Set;

/**
 *用户验证处理
 * @Auther: sunxx
 * @Date: 2024/1/13 - 01 - 13 - 12:36
 * @Description: com.sxx.ajcommunity.system.service.impl
 * @version: 1.0
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        com.csy.commons.dto.SysUser user = sysUserService.selectUserByUserName(username);

        if (Objects.isNull(user)){
            log.info("登录用户：{} 不存在",username);
            throw new UsernameNotFoundException("登录用户：" + username + "不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除",username);
            throw new BaseException("对不起，您的账号：" + username + "已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用",username);
            throw new BaseException("对不起，您的账号：" + username + "已被停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user){
        Set<String> menuPermission = permissionService.getMenuPermission(user);
        return new LoginUser(user,menuPermission);
    }
}
